#include "MessagesConsumer.h"
#include "MessageParser.h"

#define CONN_PORT 54321
#define ALLOW_LOCALHOST		//for debug

MessagesConsumer::MessagesConsumer()
{
	/** 
	 * Init a null socket
	 * (for start and stop thread that cause unable to bind socket 
	 */
	sock = NULL;
}

void MessagesConsumer::readPendingDatagrams()
{
	while (sock->hasPendingDatagrams())
	{
		QByteArray datagram;
		datagram.resize(sock->pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;
		
		sock->readDatagram(datagram.data(), datagram.size(),
		&sender, &senderPort);
		
		qDebug() << "Received MSG From: " + sender.toString() + ":" + QByteArray::number(senderPort);
		
		// parse the datagram if the sender != myself
#ifndef ALLOW_LOCALHOST
		if(!QNetworkInterface::allAddresses().contains(sender))
#endif
			MessageParser::getInstance()->parseString(&datagram, sender);
	}
}

void MessagesConsumer::run()
{
	qDebug() << "Messages Consumer thread started" << this;
	
	if(sock == NULL)
	{
		sock = new QUdpSocket();
		
		if(sock->bind(QHostAddress::Any, CONN_PORT) == false)
		{
			qWarning() << "unable to bind messages consumer socket";
			
			//TODO: emit signal!
		}
		
		//connect the readyRead signal
		connect(sock, SIGNAL(readyRead()),
				this, SLOT(readPendingDatagrams()));
	}
	exec();		//start the thread loop and wait until exit() is called
}
